import QtQuick 2.12
import QtQuick.Controls 2.12
import QtLocation 5.12
import QtPositioning 5.12
import QtQuick.Dialogs 1.3
import QtQuick.Shapes 1.12

/**
 * YCLocation地图查看器
 * 基于yclocation-master的QtLocationPlugin实现
 * 支持在线地图瓦片加载和路线规划
 */
Rectangle {
    id: ycLocationMapViewer
    color: "transparent"
    
    // 配置属性
    property real currentScale: _map.zoomLevel
    property real minScale: 3.0
    property real maxScale: 20.0
    
    // 状态属性
    property bool mapReady: false
    property bool mapLoading: true
    property bool forceReload: false
    
    // 地图中心位置（默认设置为甘蔗田位置）
    property real centerLon: 109.240150
    property real centerLat: 23.724696
    
    // 信号定义（兼容原有接口）
    signal mapReady()
    signal locationChanged(real lon, real lat)
    signal mapClicked(real lon, real lat)
    signal pathPointAdded(real lon, real lat, int index)
    signal pathPointRemoved(int index)
    signal pathChanged()
    signal scaleChanged(real scale)
    
    // 路径点模型（兼容原有接口）
    ListModel {
        id: pathPointsModel
    }
    
    // 机器人位置模型（兼容原有接口）
    ListModel {
        id: robotPositionsModel
    }
    
    // 路径规划相关属性
    property bool pathEditMode: false
    property bool showRobotPosition: true
    property real pathLineWidth: 3.0
    property color pathLineColor: "#e74c3c"
    property color pathPointColor: "#3498db"
    property color robotPositionColor: "#27ae60"
    
    // 路线站点管理（yclocation-master方式）
    property var waypoints: []
    property var routePath: []
    property bool routeMode: false
    
    // 主地图组件
    Map {
        id: _map
        anchors.fill: parent
        gesture.acceptedGestures: MapGestureArea.PinchGesture | MapGestureArea.PanGesture | MapGestureArea.FlickGesture
        gesture.flickDeceleration: 3000
        minimumZoomLevel: minScale
        maximumZoomLevel: maxScale
        zoomLevel: 10
        center: QtPositioning.coordinate(centerLat, centerLon)
        
        // 使用YCLocationProvider插件
        plugin: Plugin { 
            name: "YCLocationProvider"
        }
        
        // 点击地图获取经纬度
        MouseArea {
            anchors.fill: parent
            onClicked: {
                // 将屏幕坐标转换为地理坐标（经纬度）
                var coordinate = _map.toCoordinate(Qt.point(mouse.x, mouse.y))
                console.log("YCLocation地图点击坐标：", coordinate.latitude, coordinate.longitude)
                
                // 发出地图点击信号
                ycLocationMapViewer.mapClicked(coordinate.longitude, coordinate.latitude)
                
                // 如果处于路径编辑模式，添加路径点
                if (pathEditMode) {
                    addPathPoint(coordinate.longitude, coordinate.latitude)
                }
                
                // 如果处于路线规划模式，显示站点选择对话框
                if (routeMode) {
                    addWaypointDialog.coordinate = coordinate
                    addWaypointDialog.open()
                }
            }
        }
        
        // 地图中心变化信号
        onCenterChanged: {
            ycLocationMapViewer.locationChanged(center.longitude, center.latitude)
        }
        
        // 地图缩放变化信号
        onZoomLevelChanged: {
            ycLocationMapViewer.scaleChanged(zoomLevel)
        }
        
        // 使用Canvas绘制路径和标记
        Canvas {
            id: routeCanvas
            anchors.fill: parent
            // 添加recursive属性以解决ShaderEffectSource递归渲染问题
            recursive: true
            
            onPaint: {
                var ctx = getContext("2d")
                ctx.clearRect(0, 0, width, height)
                
                // 绘制路径点连线
                if (pathPointsModel.count > 1) {
                    ctx.strokeStyle = pathLineColor
                    ctx.lineWidth = pathLineWidth
                    ctx.beginPath()
                    
                    for (var i = 0; i < pathPointsModel.count; i++) {
                        var item = pathPointsModel.get(i)
                        var point = _map.fromCoordinate(QtPositioning.coordinate(item.lat, item.lon))
                        if (i === 0) {
                            ctx.moveTo(point.x, point.y)
                        } else {
                            ctx.lineTo(point.x, point.y)
                        }
                    }
                    ctx.stroke()
                }
                
                // 绘制路径点
                for (var j = 0; j < pathPointsModel.count; j++) {
                    var pathItem = pathPointsModel.get(j)
                    var pathPoint = _map.fromCoordinate(QtPositioning.coordinate(pathItem.lat, pathItem.lon))
                    
                    // 绘制圆形路径点
                    ctx.fillStyle = pathPointColor
                    ctx.strokeStyle = "white"
                    ctx.lineWidth = 2
                    ctx.beginPath()
                    ctx.arc(pathPoint.x, pathPoint.y, 8, 0, 2 * Math.PI)
                    ctx.fill()
                    ctx.stroke()
                    
                    // 绘制路径点编号
                    ctx.fillStyle = "white"
                    ctx.font = "bold 10px Arial"
                    ctx.textAlign = "center"
                    ctx.textBaseline = "middle"
                    ctx.fillText((j + 1).toString(), pathPoint.x, pathPoint.y)
                }
                
                // 绘制机器人位置
                if (showRobotPosition) {
                    for (var k = 0; k < robotPositionsModel.count; k++) {
                        var robotItem = robotPositionsModel.get(k)
                        var robotPoint = _map.fromCoordinate(QtPositioning.coordinate(robotItem.lat, robotItem.lon))
                        
                        // 绘制机器人位置标记
                        ctx.fillStyle = robotPositionColor
                        ctx.strokeStyle = "white"
                        ctx.lineWidth = 2
                        ctx.beginPath()
                        ctx.arc(robotPoint.x, robotPoint.y, 12, 0, 2 * Math.PI)
                        ctx.fill()
                        ctx.stroke()
                        
                        // 绘制机器人编号
                        ctx.fillStyle = "white"
                        ctx.font = "bold 8px Arial"
                        ctx.textAlign = "center"
                        ctx.textBaseline = "middle"
                        ctx.fillText(robotItem.sn, robotPoint.x, robotPoint.y)
                    }
                }
                
                // 绘制路线规划结果
                if (routePath.length > 1) {
                    ctx.strokeStyle = "blue"
                    ctx.lineWidth = 4
                    ctx.beginPath()
                    
                    for (var l = 0; l < routePath.length; l++) {
                        var routePoint = _map.fromCoordinate(QtPositioning.coordinate(routePath[l].lat, routePath[l].lng))
                        if (l === 0) {
                            ctx.moveTo(routePoint.x, routePoint.y)
                        } else {
                            ctx.lineTo(routePoint.x, routePoint.y)
                        }
                    }
                    ctx.stroke()
                }
                
                // 绘制路线站点
                for (var m = 0; m < waypoints.length; m++) {
                    var wp = waypoints[m]
                    var wpPoint = _map.fromCoordinate(QtPositioning.coordinate(wp.lat, wp.lng))
                    
                    // 设置站点颜色
                    var color = wp.type === "start" ? "green" :
                               wp.type === "end" ? "red" : "blue"
                    
                    // 绘制圆形站点
                    ctx.fillStyle = color
                    ctx.strokeStyle = "white"
                    ctx.lineWidth = 2
                    ctx.beginPath()
                    ctx.arc(wpPoint.x, wpPoint.y, 16, 0, 2 * Math.PI)
                    ctx.fill()
                    ctx.stroke()
                    
                    // 绘制站点文字
                    ctx.fillStyle = "white"
                    ctx.font = "bold 14px Arial"
                    ctx.textAlign = "center"
                    ctx.textBaseline = "middle"
                    var text = wp.type === "start" ? "S" :
                              wp.type === "end" ? "E" : "W"
                    ctx.fillText(text, wpPoint.x, wpPoint.y)
                }
            }
            
            // 当地图移动或缩放时重新绘制
            Connections {
                target: _map
                onCenterChanged: routeCanvas.requestPaint()
                onZoomLevelChanged: routeCanvas.requestPaint()
            }
        }
    }
    
    // 添加站点的确认对话框
    Dialog {
        id: addWaypointDialog
        property var coordinate: null
        title: "添加站点"
        width: 300
        height: 200
        
        contentItem: Column {
            spacing: 10
            anchors.fill: parent
            
            Text {
                text: coordinate ? `经纬度：${coordinate.latitude.toFixed(6)}, ${coordinate.longitude.toFixed(6)}` : ""
                wrapMode: Text.WordWrap
                width: parent.width
            }
            
            Button {
                text: "设为起点"
                width: parent.width
                onClicked: {
                    // 清空已有起点，添加新起点
                    waypoints = waypoints.filter(function(w) { return w.type !== "start" })
                    var newWaypoint = {
                        lat: addWaypointDialog.coordinate.latitude,
                        lng: addWaypointDialog.coordinate.longitude,
                        type: "start"
                    }
                    waypoints.push(newWaypoint)
                    console.log("添加起点:", newWaypoint)
                    routeCanvas.requestPaint()
                    addWaypointDialog.close()
                }
            }
            
            Button {
                text: "添加途经点"
                width: parent.width
                onClicked: {
                    var newWaypoint = {
                        lat: addWaypointDialog.coordinate.latitude,
                        lng: addWaypointDialog.coordinate.longitude,
                        type: "waypoint"
                    }
                    waypoints.push(newWaypoint)
                    console.log("添加途经点:", newWaypoint)
                    routeCanvas.requestPaint()
                    addWaypointDialog.close()
                }
            }
            
            Button {
                text: "设为终点"
                width: parent.width
                onClicked: {
                    waypoints = waypoints.filter(function(w) { return w.type !== "end" })
                    var newWaypoint = {
                        lat: addWaypointDialog.coordinate.latitude,
                        lng: addWaypointDialog.coordinate.longitude,
                        type: "end"
                    }
                    waypoints.push(newWaypoint)
                    console.log("添加终点:", newWaypoint)
                    routeCanvas.requestPaint()
                    addWaypointDialog.close()
                }
            }
            
            Button {
                text: "取消"
                width: parent.width
                onClicked: addWaypointDialog.close()
            }
        }
    }
    
    // 连接路线服务信号
    Connections {
        target: typeof routeService !== 'undefined' ? routeService : null
        onRouteReady: {
            // 将后端返回的经纬度列表转换为路线路径格式
            routePath = []
            for (var i = 0; i < arguments[0].length; i++) {
                var coord = arguments[0][i]
                routePath.push({
                    lat: coord.lat,
                    lng: coord.lng
                })
            }
            routeCanvas.requestPaint()
            console.log("路线绘制完成，共", routePath.length, "个点")
        }
        
        onRouteError: {
            console.log("路线规划错误:", arguments[0])
        }
        
        onRouteProgress: {
            console.log("路线规划进度:", arguments[0] + "%")
        }
    }
    
    // 兼容原有OfflineMapViewer的方法
    function loadMap() {
        console.log("YCLocation地图加载完成")
        mapLoading = false
        mapReady = true
        ycLocationMapViewer.mapReady()
    }
    
    function setMapCenter(lon, lat) {
        centerLon = lon
        centerLat = lat
        _map.center = QtPositioning.coordinate(lat, lon)
    }
    
    function setScale(scale) {
        _map.zoomLevel = scale
    }
    
    function togglePathEditMode() {
        pathEditMode = !pathEditMode
        console.log("路径编辑模式:", pathEditMode ? "启用" : "禁用")
    }
    
    function enablePathEditMode() {
        pathEditMode = true
    }
    
    function clearPath() {
        pathPointsModel.clear()
        waypoints = []
        routePath = []
        routeCanvas.requestPaint()
        console.log("路径已清除")
    }
    
    function addPathPoint(lon, lat) {
        pathPointsModel.append({
            lon: lon,
            lat: lat
        })
        pathPointAdded(lon, lat, pathPointsModel.count - 1)
        console.log("添加路径点:", lon, lat)
        routeCanvas.requestPaint()
    }
    
    function removePathPoint(index) {
        if (index >= 0 && index < pathPointsModel.count) {
            pathPointsModel.remove(index)
            pathPointRemoved(index)
            console.log("移除路径点:", index)
            routeCanvas.requestPaint()
        }
    }
    
    function getPathPoints() {
        var points = []
        for (var i = 0; i < pathPointsModel.count; i++) {
            var item = pathPointsModel.get(i)
            points.push({
                lon: item.lon,
                lat: item.lat
            })
        }
        return points
    }
    
    function calculatePathLength() {
        // 简单的路径长度计算（直线距离）
        var totalLength = 0
        for (var i = 1; i < pathPointsModel.count; i++) {
            var prev = pathPointsModel.get(i - 1)
            var curr = pathPointsModel.get(i)
            // 使用简单的欧几里得距离
            var dx = curr.lon - prev.lon
            var dy = curr.lat - prev.lat
            totalLength += Math.sqrt(dx * dx + dy * dy) * 111000 // 粗略转换为米
        }
        return totalLength
    }
    
    function updateRobotPosition(sn, lon, lat, status) {
        // 更新机器人位置
        for (var i = 0; i < robotPositionsModel.count; i++) {
            var item = robotPositionsModel.get(i)
            if (item.sn === sn) {
                robotPositionsModel.set(i, {
                    sn: sn,
                    lon: lon,
                    lat: lat,
                    status: status
                })
                routeCanvas.requestPaint()
                return
            }
        }
        // 如果没找到，添加新的机器人位置
        robotPositionsModel.append({
            sn: sn,
            lon: lon,
            lat: lat,
            status: status
        })
        routeCanvas.requestPaint()
    }
    
    function exportPathToKML() {
        // 简单的KML导出
        var kml = '<?xml version="1.0" encoding="UTF-8"?>\n'
        kml += '<kml xmlns="http://www.opengis.net/kml/2.2">\n'
        kml += '<Document>\n'
        kml += '<Placemark>\n'
        kml += '<LineString>\n'
        kml += '<coordinates>\n'
        
        for (var i = 0; i < pathPointsModel.count; i++) {
            var item = pathPointsModel.get(i)
            kml += item.lon + ',' + item.lat + ',0\n'
        }
        
        kml += '</coordinates>\n'
        kml += '</LineString>\n'
        kml += '</Placemark>\n'
        kml += '</Document>\n'
        kml += '</kml>'
        
        return kml
    }
    
    // 路线规划相关方法
    function requestRoute() {
        if (waypoints.length >= 2) {
            var startCount = waypoints.filter(function(w) { return w.type === "start" }).length
            var endCount = waypoints.filter(function(w) { return w.type === "end" }).length
            
            if (startCount === 0 || endCount === 0) {
                console.log("请设置起点和终点")
                return
            }
            
            // 按顺序整理站点（起点->途经点->终点）
            var start = waypoints.find(function(w) { return w.type === "start" })
            var waypointList = waypoints.filter(function(w) { return w.type === "waypoint" })
            var end = waypoints.find(function(w) { return w.type === "end" })
            var orderedPoints = [start].concat(waypointList).concat([end])
            
            // 调用后端路线服务
            if (typeof routeService !== 'undefined') {
                routeService.requestRoute(orderedPoints)
            } else {
                console.log("路线服务未初始化")
            }
        }
    }
    
    function clearRoute() {
        waypoints = []
        routePath = []
        routeCanvas.requestPaint()
    }
    
    function toggleRouteMode() {
        routeMode = !routeMode
        if (!routeMode) {
            clearRoute()
        }
    }
    
    // 地图加载完成后发出信号
    Component.onCompleted: {
        console.log("YCLocation地图组件初始化")
        if (_map.supportedMapTypes.length > 0) {
            console.log("支持的地图类型:", _map.supportedMapTypes[0].name)
            _map.activeMapType = _map.supportedMapTypes[0]
        }
        // 延迟发出mapReady信号
        Qt.callLater(function() {
            loadMap()
        })
    }
}